package com.framework.bdf4j.msg.service.impl;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.framework.bdf4j.msg.constant.PublicConstant;
import com.framework.bdf4j.msg.entity.domain.SysMsgReceiver;
import com.framework.bdf4j.msg.entity.domain.SysMsgRole;
import com.framework.bdf4j.msg.entity.dto.SysMsgRoleSaveDTO;
import com.framework.bdf4j.msg.mapper.SysMsgRoleMapper;
import com.framework.bdf4j.msg.service.SysMsgReceiverService;
import com.framework.bdf4j.msg.service.SysMsgRoleService;
import com.framework.bdf4j.msg.util.DtoEntityUtil;
import com.framework.bdf4j.sysadm.service.SysUserService;

/**
 * 消息接收角色表
 *
 * @author shan.deng
 * @date 2020-08-03 11:35:03
 */
@Service
public class SysMsgRoleServiceImpl extends ServiceImpl<SysMsgRoleMapper, SysMsgRole> implements SysMsgRoleService {

    @Resource
    private SysUserService sysUserService;

    @Resource
    private SysMsgReceiverService sysMsgReceiverService;

    @Override
    @Transactional
    public Boolean saveSysMsgRoleBatch(Integer msgId ,List<SysMsgRoleSaveDTO> sysMsgRoleSaveDTOS) {

        //把角色记录保存
        if(CollectionUtils.isNotEmpty(sysMsgRoleSaveDTOS)) {
            List<Integer> roleIds = new ArrayList<>();
            List<SysMsgRole> sysMsgRoles = DtoEntityUtil.trans(sysMsgRoleSaveDTOS, SysMsgRole.class);
            sysMsgRoles.forEach(sysMsgRole -> {
                sysMsgRole.setMsgId(msgId);
                roleIds.add(sysMsgRole.getRoleId());
            });

            //将角色对应的用户保存
            List<Integer> userIds = sysUserService.getUserListByRoleId(roleIds);

            List<SysMsgReceiver> list = new ArrayList<>();

            userIds.stream().forEach(userId -> {
                SysMsgReceiver sysMsgReceiver = new SysMsgReceiver();
                sysMsgReceiver.setMsgId(msgId);
                sysMsgReceiver.setReceiverType(PublicConstant.RECEIVER_TYPE_ROLE);
                sysMsgReceiver.setReceiverUserId(userId);
                sysMsgReceiverService.save(sysMsgReceiver);
//                list.add(sysMsgReceiver);
            });
            for (SysMsgRole sysMsgRole : sysMsgRoles) {
            	this.save(sysMsgRole);
			}
//            this.saveBatch(sysMsgRoles);
//            sysMsgReceiverService.saveBatch(list);
        }
        return Boolean.TRUE;
    }
}
